package edu.xidian.onlinedocument.repository;

import edu.xidian.onlinedocument.entity.DocumentData;
import edu.xidian.onlinedocument.entity.UserData;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

@Repository
public interface DocumentJPARepository extends JpaRepository<DocumentData, Integer>, JpaSpecificationExecutor<DocumentData> {

    boolean existsDocumentDataByDocId(int docId);

    boolean existsDocumentDataByCreatorData_UserId(int userId);

    boolean existsDocumentDataByCreatorData_UserNum(String userNum);

    boolean existsDocumentDataByCreatorData_UserIdAndDocIsDeleteIsFalse(int docId);

    boolean existsDocumentDataByDocIdAndDocIsDeleteIsFalse(int docId);

    boolean existsDocumentDataByDocIdAndDocIsDeleteIsTrue(int docId);

    List<DocumentData> findAllByDocIsDeleteIsFalse();

    List<DocumentData> findAllByCreatorData_UserId(int userId);

    List<DocumentData> findAllByCreatorData_UserNum(String userNum);

    List<DocumentData> findAllByDocName(String docName);

    /**
     * 查询该用户创建的未删除的文档
     * @param userId 用户id
     * @return List<DocumentData>
     */
    List<DocumentData> findAllByCreatorData_UserIdAndDocIsDeleteIsFalse(int userId);

    /**
     * 查询该用户创建的已删除的文档
     * @param userId 用户id
     * @return List<DocumentData>
     */
    List<DocumentData> findAllByCreatorData_UserIdAndDocIsDeleteIsTrue(int userId);

    DocumentData findDocumentDataByDocId(int docId);

    DocumentData findDocumentDataByDocIdAndDocIsDeleteIsFalse(int docId);

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Modifying
    int deleteDocumentDataByCreatorData_UserNum(String userNum);

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Modifying
    int deleteDocumentDataByDocId(int docId);

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Modifying
    @Query(nativeQuery = true, value = "insert into doc_data(doc_name, user_id, doc_version, doc_create_time, doc_update_time, doc_is_delete) " +
            "values(:doc_name, :user_id, :doc_version, :doc_create_time, :doc_update_time, :doc_is_delete)")
    int addOneDocument(@Param("doc_name") String docName,
                        @Param("user_id") int userId,
                        @Param("doc_version") int docVersion,
                        @Param("doc_create_time") Date docCreateTime,
                        @Param("doc_update_time") Date docUpdateTime,
                        @Param("doc_is_delete") boolean docIsDelete);

}